﻿using System;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using ZZQFrameWork;

public class MainPanel:BaseUI
{
    private CharacterModule characterModule
    {
        get { return ModuleManager.Instance.Get<CharacterModule>(); }
    }
    private BackpackModule backpackModule
    {
        get { return ModuleManager.Instance.Get<BackpackModule>(); }
    }

    #region 角色状态

    private Text hpText;
    private Text mpText;
    private Text xpText;
    private Text goldText;
    private Slider hpSlider;
    private Slider mpSlider;
    private Slider xpSlider;

    #endregion

    #region 任务状态

    private GameObject taskPanel;
    private GridLayoutGroup taskGrid;
    private GameObject taskItemPrefab;
    private GameObject openTaskPanelButton;
    private bool isTaskPanelOpen = true;
    private List<TaskItem> taskItemList=new List<TaskItem>(); 

    #endregion

    #region 物品背包状态

    /// <summary>
    /// 奖励增加显示grid
    /// </summary>
    private GridLayoutGroup rewardGridLayoutGroup;

    /// <summary>
    /// 背包按钮
    /// </summary>
    private GameObject bagGameObject;

    /// <summary>
    /// 详细信息界面
    /// </summary>
    private GameObject moreInfoPanel;

    /// <summary>
    /// 详细信息界面的grid
    /// </summary>
    private GridLayoutGroup moreInfoGrid;

    /// <summary>
    /// 详细界面中拥有的所有物品集合
    /// </summary>
    private List<GameObject> nowMoreInfoPanelGameObjectList=new List<GameObject>(); 

    /// <summary>
    /// 主界面底框下面的5个物品格子
    /// </summary>
    private MainPanelGoodsItem[] downBarGoodsItems;

    /// <summary>
    /// 当前选中的格子
    /// </summary>
    private MainPanelGoodsItem currentGoodsItem;

    /// <summary>
    /// 打开关闭详细信息界面按钮
    /// </summary>
    private GameObject openMoreInfoButton;

    /// <summary>
    /// 详细信息界面是否开启
    /// </summary>
    private bool isOpenMoreInfo = false;

    /// <summary>
    /// 拖拽时的image
    /// </summary>
    private MainPanelDragGoodsItem dragGoodsItem;

    public MainPanelDragGoodsItem DragGoodsItem
    {
        get {
            if (dragGoodsItem == null)
            {
                GameObject go = new GameObject("DragGoodsItem", typeof(RectTransform));
                go.AddComponent<CanvasGroup>().blocksRaycasts = false;
                RectTransform rect = go.GetComponent<RectTransform>();
                rect.SetParent(transform, false);
                rect.SetAsLastSibling();
                dragGoodsItem=go.GetOrAddComponent<MainPanelDragGoodsItem>();
            }
            return dragGoodsItem;
        }
    }

    #endregion

    public override Enum_UIType GetUIType()
    {
        return Enum_UIType.MainPanel;
    }

    protected override void OnAwake()
    { 
        hpText = transform.GetComponentByPath<Text>("PlayerState/Hp/Text");
        mpText = transform.GetComponentByPath<Text>("PlayerState/Mp/Text");
        xpText = transform.GetComponentByPath<Text>("PlayerState/Xp/Text");
        goldText = transform.GetComponentByPath<Text>("PlayerState/Gold/Text");
        hpSlider = transform.GetComponentByPath<Slider>("PlayerState/Hp/Slider");
        mpSlider = transform.GetComponentByPath<Slider>("PlayerState/Mp/Slider");
        xpSlider = transform.GetComponentByPath<Slider>("PlayerState/Xp/Slider");

        taskPanel = transform.Find("PlayerTask/BG").gameObject;
        taskGrid = transform.Find("PlayerTask").GetComponentInChildren<GridLayoutGroup>();
        taskItemPrefab = ResManager.Instance.Load("TaskItem") as GameObject;
        openTaskPanelButton = transform.Find("PlayerTask/OpenButton").gameObject;

        rewardGridLayoutGroup = transform.GetComponentByPath<GridLayoutGroup>("RewardGrid");
        moreInfoPanel = transform.Find("GoodsMoreInfo").gameObject;
        moreInfoGrid = moreInfoPanel.GetComponentInChildren<GridLayoutGroup>();
        bagGameObject = transform.Find("DownBar/Bag").gameObject;
        downBarGoodsItems = transform.Find("DownBar").GetComponentsInChildren<MainPanelGoodsItem>();
        openMoreInfoButton = transform.Find("DownBar/OpenMore").gameObject;

        EventTriggerListener.Get(openTaskPanelButton).SetEventHandle(Enum_TouchEventType.OnClick, OnChangeTaskPanelState);
        EventTriggerListener.Get(bagGameObject).SetEventHandle(Enum_TouchEventType.OnClick, OnOpenBag);
        for (int i = 0; i < downBarGoodsItems.Length; i++)
        {
            OnRegisterGoodsItemEventListener(downBarGoodsItems[i].gameObject);
        }
        EventTriggerListener.Get(openMoreInfoButton).SetEventHandle(Enum_TouchEventType.OnClick, OnOpenMoreInfo);
    }

    protected override void OnStart()
    {
        RefreshPanel();
    }

    void OnEnable()
    {
        EventDispatcher.AddListener<int,int>(Events.RoleEvent.OnUpdateHp, OnUpdateHp);
        EventDispatcher.AddListener<int, int>(Events.RoleEvent.OnUpdateMp, OnUpdateMp);
        EventDispatcher.AddListener<int, int>(Events.RoleEvent.OnUpdateExp, OnUpdateExp);
        EventDispatcher.AddListener<int>(Events.RoleEvent.OnUpdateGold, OnUpdateGold);
        EventDispatcher.AddListener<int>(Events.RoleEvent.OnUpdateLv, OnUpdateLv);

        EventDispatcher.AddListener<TaskData>(Events.TaskEvent.AcceptTask, OnAcceptTask);
        EventDispatcher.AddListener<TaskData>(Events.TaskEvent.UpdateTask, OnUpdateTask);
        EventDispatcher.AddListener<int>(Events.TaskEvent.FinishTask, OnFinishTask);
        EventDispatcher.AddListener<int>(Events.TaskEvent.FinishTaskToNpc, OnFinishTaskToNpc);

        EventDispatcher.AddListener<GoodsVO>(Events.CharacterEvent.OnAddItem, OnAddRewardGoods);
        EventDispatcher.AddListener<GoodsVO>(Events.CharacterEvent.OnRemoveItem, OnRemoveGoodsItem);
        EventDispatcher.AddListener<GoodsVO>(Events.CharacterEvent.OnUpdateItem,OnUpdateGoodsItem);

    }

    void OnDisable()
    {
        EventDispatcher.RemoveListener<int, int>(Events.RoleEvent.OnUpdateHp, OnUpdateHp);
        EventDispatcher.RemoveListener<int, int>(Events.RoleEvent.OnUpdateMp, OnUpdateMp);
        EventDispatcher.RemoveListener<int, int>(Events.RoleEvent.OnUpdateExp, OnUpdateExp);
        EventDispatcher.RemoveListener<int>(Events.RoleEvent.OnUpdateGold, OnUpdateGold);

        EventDispatcher.RemoveListener<TaskData>(Events.TaskEvent.AcceptTask, OnAcceptTask);
        EventDispatcher.RemoveListener<TaskData>(Events.TaskEvent.UpdateTask, OnUpdateTask);
        EventDispatcher.RemoveListener<int>(Events.TaskEvent.FinishTask, OnFinishTask);
        EventDispatcher.RemoveListener<int>(Events.TaskEvent.FinishTaskToNpc, OnFinishTaskToNpc);

        EventDispatcher.RemoveListener<GoodsVO>(Events.CharacterEvent.OnAddItem, OnAddRewardGoods);
        EventDispatcher.RemoveListener<GoodsVO>(Events.CharacterEvent.OnRemoveItem, OnRemoveGoodsItem);
        EventDispatcher.RemoveListener<GoodsVO>(Events.CharacterEvent.OnUpdateItem, OnUpdateGoodsItem);
    }

    protected override void OnPlayMusic()
    {
        SoundManager.Instance.PlayMusic("1002");
    }

    /// <summary>
    /// 刷新界面
    /// </summary>
    void RefreshPanel()
    {
        RoleDataVO vo = characterModule.mainRole;
        OnUpdateGold(vo.gold);
        OnUpdateExp(vo.exp,vo.maxExp);
        OnUpdateHp(vo.hp,vo.maxHp);
        OnUpdateLv(vo.lv);
        OnUpdateMp(vo.mp,vo.maxMp);
        for (int i = 0; i < vo.taskDataList.Count; i++)
        {
            OnAcceptTask(vo.taskDataList[i]);
        }
    }

    #region 角色数值操作

    private void OnUpdateGold(int gold)
    {
        goldText.text = gold.ToString();
    }

    private void OnUpdateExp(int exp, int maxExp)
    {
        Debug.Log("当前经验"+exp+"需要经验："+maxExp);
        //xpText.text = exp + "/" + maxExp;
        xpSlider.value = (float) exp/maxExp;
    }

    private void OnUpdateLv(int lv)
    {
        RoleDataVO vo = characterModule.mainRole;
        xpText.text = "LV" + lv;
        OnUpdateExp(vo.exp, vo.maxExp);
        OnUpdateHp(vo.hp, vo.maxHp);
        OnUpdateMp(vo.mp, vo.maxMp);
    }

    private void OnUpdateMp(int mp, int maxMp)
    {
        mpText.text = mp + "/" + maxMp;
        mpSlider.value = (float)mp / maxMp;
    }

    private void OnUpdateHp(int hp, int maxHp)
    {
        hpText.text = hp + "/" + maxHp;
        hpSlider.value = (float)hp / maxHp;
    }

    #endregion

    #region 任务操作

    /// <summary>
    /// 接受任务
    /// </summary>
    /// <param name="task"></param>
    private void OnAcceptTask(TaskData task)
    {
        foreach (TaskItem item in taskItemList)
        {
            if (item.Data.id == task.id)
            {
                OnUpdateTask(task);
                return;
            }
        }
        taskItemList.Add(CreatTaskItem(task));
    }

    /// <summary>
    /// 更新任务
    /// </summary>
    /// <param name="task"></param>
    private void OnUpdateTask(TaskData task)
    {
        foreach (TaskItem item in taskItemList)
        {
            if (item.Data.id == task.id)
            {
                item.UpdateProgress(Enum_TaskProgress.Unfinished);
                return;
            }
        }
    }

    /// <summary>
    /// 完成任务
    /// </summary>
    /// <param name="id"></param>
    private void OnFinishTask(int id)
    {
        foreach (TaskItem item in taskItemList)
        {
            if (item.Data.id == id)
            {
                item.UpdateProgress(Enum_TaskProgress.Finished);
                return;
            }
        }
    }

    /// <summary>
    /// 交任务
    /// </summary>
    /// <param name="id"></param>
    private void OnFinishTaskToNpc(int id)
    {
        Debug.Log("需要交任务的id:"+id+"任务集合数量："+taskItemList.Count);
        //foreach (TaskItem item in taskItemList)
        //{
        //    Debug.Log("id:"+item.Data.id);
        //    if (item.Data.id == id)
        //    {
        //        item.UpdateProgress(Enum_TaskProgress.FinishToNpc);
        //        return;
        //    }
        //}
        TaskItem item = taskItemList.Find((obj) =>
        {
            return obj.Data.id == id;
        });
        item.UpdateProgress(Enum_TaskProgress.FinishToNpc);
        taskItemList.Remove(item);
    }

    /// <summary>
    /// 创建任务item
    /// </summary>
    /// <param name="task"></param>
    /// <returns></returns>
    private TaskItem CreatTaskItem(TaskData task)
    {
        GameObject go = Instantiate(taskItemPrefab);
        go.transform.SetParent(taskGrid.transform, false);
        TaskItem item = go.GetOrAddComponent<TaskItem>();
        item.Data = task;
        return item;
    }

    /// <summary>
    /// 改变任务界面状态，开启或者隐藏
    /// </summary>
    /// <param name="_listener"></param>
    /// <param name="_args"></param>
    /// <param name="_params"></param>
    private void OnChangeTaskPanelState(GameObject _listener, object _args, object[] _params)
    {
        isTaskPanelOpen = !isTaskPanelOpen;
        taskPanel.SetActive(isTaskPanelOpen);
    }
    #endregion

    #region 底框物品背包操作

    /// <summary>
    /// 打开背包
    /// </summary>
    /// <param name="_listener"></param>
    /// <param name="_args"></param>
    /// <param name="_params"></param>
    private void OnOpenBag(GameObject _listener, object _args, object[] _params)
    {
        UIManager.Instance.OpenUI(Enum_UIOpenType.OpenSelf, Enum_UIType.CharacterMainPanel);
    }

    /// <summary>
    /// 物品被点击
    /// </summary>
    /// <param name="_listener"></param>
    /// <param name="_args"></param>
    /// <param name="_params"></param>
    private void OnGoodsItemClick(GameObject _listener, object _args, object[] _params)
    {
        MainPanelGoodsItem item = _listener.GetComponent<MainPanelGoodsItem>();
        if (item.Data == null)
        {
            if (currentGoodsItem != null)
            {
                currentGoodsItem.SetItemClicked(false);
                currentGoodsItem = null;
            }
            return;
        }
        if (item == currentGoodsItem)
        {
            //使用物品
            backpackModule.OnUseGoods(item.Data);
            return;
        }
        if(currentGoodsItem!=null)currentGoodsItem.SetItemClicked(false);
        currentGoodsItem = item;
        currentGoodsItem.SetItemClicked(true);
    }

    /// <summary>
    /// 开启关闭详细信息界面
    /// </summary>
    /// <param name="_listener"></param>
    /// <param name="_args"></param>
    /// <param name="_params"></param>
    private void OnOpenMoreInfo(GameObject _listener, object _args, object[] _params)
    {
        isOpenMoreInfo = !isOpenMoreInfo;
        moreInfoPanel.SetActive(isOpenMoreInfo);
        if (isOpenMoreInfo) OnRefreshGoodsMoreInfoPanel();
    }

    /// <summary>
    /// 刷新详细信息界面
    /// </summary>
    private void OnRefreshGoodsMoreInfoPanel()
    {
        List<GoodsVO> list=backpackModule.GetGoodsListVOByGoodsType(Enum_GoodsType.Consumables);
        if (list != null && list.Count > 0)
        {
            Debug.Log("有物品类型数量：" + nowMoreInfoPanelGameObjectList.Count);
            if (nowMoreInfoPanelGameObjectList.Count != list.Count)
                nowMoreInfoPanelGameObjectList = PoolManager.Instance.SpawnNeedGameObjects("MainPanelGoodsItem",
                    list.Count, nowMoreInfoPanelGameObjectList);

            for (int i = 0; i < nowMoreInfoPanelGameObjectList.Count; i++)
            {
                GameObject go= nowMoreInfoPanelGameObjectList[i];
                go.GetComponent<MainPanelGoodsItem>().Data = list[i];
                go.transform.SetParent(moreInfoGrid.transform,false);
                OnRegisterGoodsItemEventListener(go);
            }
        }
        else
        {
            for (int i = 0; i < nowMoreInfoPanelGameObjectList.Count; i++)
            {
                PoolManager.Instance.UnSpawn(nowMoreInfoPanelGameObjectList[i]);
            }
            nowMoreInfoPanelGameObjectList.Clear();
        }
    }

    private void OnRegisterGoodsItemEventListener(GameObject goodsItem)
    {
        EventTriggerListener.Get(goodsItem).SetEventHandle(Enum_TouchEventType.OnClick, OnGoodsItemClick);
        EventTriggerListener.Get(goodsItem).SetEventHandle(Enum_TouchEventType.OnDrag, OnGoodsItemDrag);
        EventTriggerListener.Get(goodsItem).SetEventHandle(Enum_TouchEventType.OnDragBegin, OnGoodsItemDragBegin);
        EventTriggerListener.Get(goodsItem).SetEventHandle(Enum_TouchEventType.OnDragEnd, OnGoodsItemDragEnd);
    }

    #region GoodsItem拖拽

    private void OnGoodsItemDrag(GameObject _listener, object _args, object[] _params)
    {
        DragGoodsItem.GetComponent<RectTransform>().position = Input.mousePosition;
    }

    private void OnGoodsItemDragBegin(GameObject _listener, object _args, object[] _params)
    {
        MainPanelGoodsItem item = _listener.GetComponent<MainPanelGoodsItem>();
        if(item.Data==null)return;
        DragGoodsItem.gameObject.SetActive(true);
        DragGoodsItem.Data = item.Data;
        DragGoodsItem.SetImage(item.GetIconImage());
    }

    private void OnGoodsItemDragEnd(GameObject _listener, object _args, object[] _params)
    {
        PointerEventData data = _args as PointerEventData;
        if (data != null && data.pointerEnter!=null)
        {
            MainPanelGoodsItem item = data.pointerEnter.GetComponent<MainPanelGoodsItem>();
            if (Array.IndexOf(downBarGoodsItems, item) != -1)
            {
                item.Data = DragGoodsItem.Data;
            }
        }
        DragGoodsItem.gameObject.SetActive(false);
    }

    #endregion

    /// <summary>
    /// 刷新goodsItem显示
    /// </summary>
    /// <param name="goods"></param>
    private void OnUpdateGoodsItem(GoodsVO goods)
    {
        for (int i = 0; i < downBarGoodsItems.Length; i++)
        {
            if(downBarGoodsItems[i].Data==null)continue;
            if (downBarGoodsItems[i].Data.id == goods.id)
            {
                downBarGoodsItems[i].Data = goods;
            }
        }
        if(moreInfoPanel.activeInHierarchy)
        OnRefreshGoodsMoreInfoPanel();
    }

    /// <summary>
    /// 删除goodsItem显示
    /// </summary>
    /// <param name="obj"></param>
    private void OnRemoveGoodsItem(GoodsVO goods)
    {
        for (int i = 0; i < downBarGoodsItems.Length; i++)
        {
            if (downBarGoodsItems[i].Data == null) continue;
            if (downBarGoodsItems[i].Data.uid == goods.uid)
            {
                downBarGoodsItems[i].Data =null;
            }
        }
        if (moreInfoPanel.activeInHierarchy)
            OnRefreshGoodsMoreInfoPanel();
    }

    /// <summary>
    /// 增加奖励物品
    /// </summary>
    /// <param name="goods"></param>
    private void OnAddRewardGoods(GoodsVO goods)
    {
        GameObject go = PoolManager.Instance.Spawn("MainPanelRewardGoodsItem");
        go.transform.SetParent(rewardGridLayoutGroup.transform, false);
        MainPanelRewardGoodsItem item = go.GetComponent<MainPanelRewardGoodsItem>();
        item.SetData(goods,goods.count);

        Tweener tweener = go.GetComponent<CanvasGroup>().DOFade(0, 2f);
        tweener.OnComplete(() =>
        {
            go.GetComponent<CanvasGroup>().alpha = 1;
            PoolManager.Instance.UnSpawn(go);
            go = null;
            item = null;
            tweener.Kill();
        });
    }

    #endregion

}
